package org.example.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.example.util.JWTUtil;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ChannelHandler.Sharable
public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public Map<String, Channel> cmap = new HashMap<>();
    private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接，通道开启！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！");
        channels.remove(ctx.channel());
        // 移除对应的ID
        cmap.entrySet().removeIf(entry -> entry.getValue() == ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            String messageText = msg.text();
            System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), messageText));

            // 解析JSON消息
            JSONObject jsonObject = JSON.parseObject(messageText);
            String type = jsonObject.getString("type");

            if ("authenticate".equals(type)) {
                String token= jsonObject.getString("token");
                Map<String, Object> c= JWTUtil.parseToken(token);
                String from=(String)(c.get("Email"));
                channels.add(ctx.channel());
                cmap.put(from, ctx.channel());
                System.out.println("通道id设置为"+ctx.channel().id());
            } else if ("message".equals(type)) {
                String to = jsonObject.getString("to");
                String from = jsonObject.getString("from");
                String content = jsonObject.getString("message");
                System.out.println("来源通道id为"+ctx.channel().id());
                // 构建要发送的消息
                JSONObject response = new JSONObject();
                response.put("type", "message");
                response.put("from", from);
                response.put("content", content);

                // 广播消息给指定的用户
                for (Map.Entry<String, Channel> entry : cmap.entrySet()) {
                    if (entry.getKey().equals(to)) {
                        entry.getValue().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
                        break;
                    }
                }
            }
            else if ("Allmessage".equals(type)) {
                      String from = jsonObject.getString("from");
                      String content = jsonObject.getString("message");
                      System.out.println("群聊信息:来源通道id为"+ctx.channel().id());
                      // 构建要发送的消息
                      JSONObject response = new JSONObject();
                      response.put("type", "Allmessage");
                      response.put("from", from);
                      response.put("content", content);

                      // 广播消息给指定的用户
                      for (Map.Entry<String, Channel> entry : cmap.entrySet()) {
                          if (!entry.getKey().equals(from)){
                              entry.getValue().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
                              break;//全部广播放送在线用户
                          }
                      }
            }
            else if ("Groupmessage".equals(type)) {
                String from = jsonObject.getString("from");
                String content = jsonObject.getString("message");
                JSONArray toUsers = jsonObject.getJSONArray("to"); // 获取群组成员数组

                System.out.println("群聊信息: 来源用户 " + from);

                // 构建要发送的消息
                JSONObject response = new JSONObject();
                response.put("type", "Groupmessage");
                response.put("from", from);
                response.put("content", content);
                response.put("groupId", jsonObject.getString("groupId")); // 添加群组ID

                // 发送给群组所有成员（除了发送者自己）
                for (Map.Entry<String, Channel> entry : cmap.entrySet()) {
                    if (!entry.getKey().equals(from) && containsUser(toUsers, entry.getKey())) {
                        entry.getValue().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
                    }
                }
            }
    }

    // 辅助方法：检查用户是否在群组成员列表中
    private boolean containsUser(JSONArray users, String email) {
        for (int i = 0; i < users.size(); i++) {
            JSONObject user = users.getJSONObject(i);
            if (user.getString("userEmail").equals(email)) {
                return true;
            }
        }
        return false;
    }
}
